package diona.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * User: anton
 * Date: 13.03.11 20:25
 */
public abstract class HklDao
{
    private static Logger LOG = LoggerFactory.getLogger(HklDao.class);

    protected final JdbcTemplate jdbcTemplate;

    protected HklDao(JdbcTemplate jdbcTemplate)
    {
        this.jdbcTemplate = jdbcTemplate;
    }

    /**
     * Implementations should initialize specific parts of db (tables, indexes etc related to the dao).
     */
    public abstract void initDb();

    protected boolean checkTableExists(String tableName)
    {
        return jdbcTemplate.query("select count(*) from INFORMATION_SCHEMA.Tables where table_name=?",
                new ResultSetExtractor<Boolean>()
                {
                    public Boolean extractData(ResultSet rs) throws SQLException, DataAccessException
                    {
                        return rs.next() && rs.getInt(1) > 0;
                    }
                }, tableName);
    }

    /**
     * Creates table with name {@code table} if it not exists
     * @param table table to create
     * @param createScript script for table creation.
     */
    protected void createTableIfNotExists(String table, String createScript)
    {
        LOG.debug("Ckecking whether table {} exists", table);
        if (!checkTableExists(table)) {
            LOG.debug("Table {} not exists. Creating...", table);
            jdbcTemplate.execute(createScript);
            LOG.debug("Table {} created", table);
        } else {
            LOG.debug("Table {} already exists", table);
        }
    }
}
